# coding: UTF-8
# Filename : chain_replylist_api.py
# Company : imedia
# Author : zqz 
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils,const,xml_tpl, err_tpl
import chain_replylist_data_model
from django.shortcuts import render_to_response
import time
'''
http://api.imedia.com/app/part/list
'''
		
#details list
def chain_replylist_list(request):
    '''
    查询后台和app端对评论的回复
    后台回复标识 source 2
    app 回复标识 source 1 
    '''
    #record log((frist action))
    httputils.footprint(request)

    if validate(request):
        return validate(request)
    #param
    comment_id = httputils.post(request, 'comment_id')#is customer id,more
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    if not utils.is_num(size): size = 1000 
    if not utils.is_num(pagenum): pagenum = 1
    #r_list = get_body_str(comment_id, size, pagenum)
    r_list = get_all_reply(comment_id)
    return render_to_response('comment/replylist.xml',{'r_list':r_list}, mimetype="application/xhtml+xml")
#数据访问
def get_body_str(comment_id,  size, pagenum):
    '''
    获取回复信息,source 状态决定加载的模板, 
    '''
    #sql
    sql = '''
    select `id`, created_at, content, source 
    from chain_comment  
    where reply_id = %s order by id desc 
    limit %s, %s 
    '''
    start_row = utils.get_star_row(size, pagenum)
    param = [int(comment_id), start_row, int(size)]
    rsts = mysql.doSearch(sql, param)
    bidui = ('id','created_at','content','source')#索引比对
    a_list = []
    for obj in rsts:
        rsts1 = dict(zip(bidui, obj))
        a_list.append(rsts1)

    return a_list 

#获取某条评论的所有回复
def get_all_reply(comment_id):
	rsts = []
	bidui = ('id','created_at','content','source')#索引比对
	while True:
		sql = '''select `id`, created_at, content, source 
	    from chain_comment
	    where reply_id = %s order by id desc'''
		reply_obj = mysql.get(sql, [comment_id])
		if reply_obj != None:
			rsts.append(dict(zip(bidui, reply_obj)))
			comment_id = reply_obj[0]
			continue
		else:
			break
	return rsts
			